package cool.mylog.mylog2end.controller;

import com.alibaba.fastjson2.JSON;
import cool.mylog.mylog2end.bean.Relation;
import cool.mylog.mylog2end.mapper.RelationMapper;
import cool.mylog.mylog2end.utils.JwtUtils;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * relation
 */
@RestController
@RequestMapping("relation")
public class RelationController {

    @Resource
    RelationMapper relationMapper;

    /**
     * get_relations 获取全部relation
     *
     * @param token 用户令牌
     * @return Log对象列表
     */
    @GetMapping("get_relations")
    public List<Relation> getRelations(String token) {
        Long id = JwtUtils.getId(token);
        if (id == 0) return null;

        return relationMapper.getRelationsByUserId(id);
    }

    /**
     * new_relation 新建relation
     *
     * @param token        用户令牌
     * @param relationJson relation的json字符串
     * @return 新建的relation id
     */
    @PostMapping("new_relation")
    public Long newRelation(String token, String relationJson) {
        Long userid = JwtUtils.getId(token);
        if (userid == 0) return 0L;
        String username = JwtUtils.getName(token);

        Relation relation = JSON.parseObject(relationJson, Relation.class);
        relation.setUserid(userid);
        relation.setUsername(username);
        System.out.println("发布Relation: " + relation);

        relationMapper.insertRelation(relation);
        return relation.getId();
    }

    /**
     * update_relation 编辑relation
     *
     * @param token        用户令牌
     * @param relationJson edit对象
     * @return 影响的条数
     */
    @PostMapping("update_relation")
    public Integer updateRelation(String token, String relationJson) {
        Long userid = JwtUtils.getId(token);
        if (userid == 0) return 0;
        Relation relation = Relation.getRelationByJson(relationJson);
        relation.setUserid(userid); // 通过token拿id
        relation.setUsername(JwtUtils.getName(token));
        System.out.println("更新relation: " + relation);
        return relationMapper.updateRelation(relation);
    }

    /**
     * delete_relation 删除relation
     *
     * @param token 用户令牌
     * @param id    relation的id
     * @return 删除的条数
     */
    @PostMapping("delete_relation")
    public Integer deleteRelation(String token, Long id) {
        Long userid = JwtUtils.getId(token);
        if (userid == 0) return 0;
        return relationMapper.deleteRelation(id, userid);
    }
}
